﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace YH.Bluetooth
{
    public class FlexoSlpUtil
    {

        public static FlexoDllUtil flexoDllUtil;

        public static int START = 0;

        public static int S = 2000;

        public FlexoSlpUtil() 
        {
            flexoDllUtil = new FlexoDllUtil();
            FlexoDllUtil.init();
        }
        public FlexoData GetEeg(float[] eegArr, float[] accXArr, float[] accYArr, float[] accZArr)
        {
            try
            {
                string data = FlexoDllUtil.getEeg(eegArr, eegArr.Length, accXArr, accYArr, accZArr, accXArr.Length, S);
                if (data.Equals("SLP not initialized"))
                {
                    Console.WriteLine("SLP not initialized");
                } 
                else if (!data.Equals("-1")) 
                {
                    try
                    {
                        // 兼容算法 NaN 问题，将字符串中的 "nan" 替换为 "0.0"
                        data = Regex.Replace(data, "(?i:\"?nan\"?)", "0.0");
                        // 反序列化 JSON 字符串到 FlexoData 类型的对象
                        FlexoData flexoData = JsonConvert.DeserializeObject<FlexoData>(data);
                        return flexoData;
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine($"Failed to parse data: {data}");
                        Console.Error.WriteLine(ex);
                        throw; // 重新抛出异常以便调用者可以处理
                    }
                }
                return null;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return null;
            }

        }
        /// <summary>
        /// 停止计算，清空缓存池
        /// </summary>
        public void stop()
        {
            FlexoDllUtil.stop();
        }
        /// <summary>
        /// 初始化算法
        /// </summary>
        public void init()
        {
            FlexoDllUtil.init();
        }
    }
}
